package com.css.zfzx.sjcj.modules.hddcB1GeologySvyProjectTable.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB1GeologySvyProjectTable.repository.HddcB1GeologysvyprojecttableNativeRepository;
import com.css.zfzx.sjcj.modules.hddcB1GeologySvyProjectTable.repository.HddcB1GeologysvyprojecttableRepository;
import com.css.zfzx.sjcj.modules.hddcB1GeologySvyProjectTable.repository.entity.HddcB1GeologysvyprojecttableEntity;
import com.css.zfzx.sjcj.modules.hddcB1GeologySvyProjectTable.service.HddcB1GeologysvyprojecttableService;
import com.css.zfzx.sjcj.modules.hddcB1GeologySvyProjectTable.viewobjects.HddcB1GeologysvyprojecttablePageVO;
import com.css.zfzx.sjcj.modules.hddcB1GeologySvyProjectTable.viewobjects.HddcB1GeologysvyprojecttableQueryParams;
import com.css.zfzx.sjcj.modules.hddcB1GeologySvyProjectTable.viewobjects.HddcB1GeologysvyprojecttableVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 地质调查数据-地质调查工程表-属性表管理
 * @author zyb
 * @date 2020-11-30
 */
@Service
public class HddcB1GeologysvyprojecttableServiceImpl implements HddcB1GeologysvyprojecttableService {

    private final HddcB1GeologysvyprojecttableRepository hddcB1GeologysvyprojecttableRepository;
    private final HddcB1GeologysvyprojecttableNativeRepository hddcB1GeologysvyprojecttableNativeRepository;
    private final GeologySurveyProjectTableExcelVerifyHandler geologySurveyProjectTableExcelVerifyHandler;

    @Autowired
    public HddcB1GeologysvyprojecttableServiceImpl(HddcB1GeologysvyprojecttableRepository hddcB1GeologysvyprojecttableRepository,
                                                   HddcB1GeologysvyprojecttableNativeRepository hddcB1GeologysvyprojecttableNativeRepository,
                                                   GeologySurveyProjectTableExcelVerifyHandler geologySurveyProjectTableExcelVerifyHandler) {
        this.hddcB1GeologysvyprojecttableRepository = hddcB1GeologysvyprojecttableRepository;
        this.hddcB1GeologysvyprojecttableNativeRepository = hddcB1GeologysvyprojecttableNativeRepository;
        this.geologySurveyProjectTableExcelVerifyHandler = geologySurveyProjectTableExcelVerifyHandler;
    }

    @Override
    public JSONObject queryHddcB1Geologysvyprojecttables(HddcB1GeologysvyprojecttableQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcB1GeologysvyprojecttablePageVO> hddcB1GeologysvyprojecttablePage = this.hddcB1GeologysvyprojecttableNativeRepository.queryHddcB1Geologysvyprojecttables(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcB1GeologysvyprojecttablePage);
    }


    @Override
    public HddcB1GeologysvyprojecttableEntity getHddcB1Geologysvyprojecttable(String id) {
        return this.hddcB1GeologysvyprojecttableRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB1GeologysvyprojecttableEntity saveHddcB1Geologysvyprojecttable(HddcB1GeologysvyprojecttableEntity hddcB1Geologysvyprojecttable) {
        String uuid = UUIDGenerator.getUUID();
        hddcB1Geologysvyprojecttable.setUuid(uuid);
        hddcB1Geologysvyprojecttable.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcB1Geologysvyprojecttable.setCreateTime(now);
        hddcB1Geologysvyprojecttable.setUpdateTime(now);
        hddcB1Geologysvyprojecttable.setIsValid(PlatformConstants.Y);
        hddcB1Geologysvyprojecttable.setQualityinspectionStatus(PlatformConstants.N);
        hddcB1Geologysvyprojecttable.setExtends10(PlatformConstants.Y);
        this.hddcB1GeologysvyprojecttableRepository.save(hddcB1Geologysvyprojecttable);
        return hddcB1Geologysvyprojecttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB1GeologysvyprojecttableEntity updateHddcB1Geologysvyprojecttable(HddcB1GeologysvyprojecttableEntity hddcB1Geologysvyprojecttable) {
        HddcB1GeologysvyprojecttableEntity entity = hddcB1GeologysvyprojecttableRepository.findById(hddcB1Geologysvyprojecttable.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcB1Geologysvyprojecttable);
        hddcB1Geologysvyprojecttable.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcB1Geologysvyprojecttable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcB1GeologysvyprojecttableRepository.save(hddcB1Geologysvyprojecttable);
        return hddcB1Geologysvyprojecttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcB1Geologysvyprojecttables(List<String> ids) {
        List<HddcB1GeologysvyprojecttableEntity> hddcB1GeologysvyprojecttableList = this.hddcB1GeologysvyprojecttableRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcB1GeologysvyprojecttableList) && hddcB1GeologysvyprojecttableList.size() > 0) {
            for(HddcB1GeologysvyprojecttableEntity hddcB1Geologysvyprojecttable : hddcB1GeologysvyprojecttableList) {
//                this.hddcB1GeologysvyprojecttableRepository.delete(hddcB1Geologysvyprojecttable);
                hddcB1Geologysvyprojecttable.setIsValid(PlatformConstants.N);
                hddcB1Geologysvyprojecttable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcB1Geologysvyprojecttable.setUpdateTime(new Date());
                this.hddcB1GeologysvyprojecttableRepository.save(hddcB1Geologysvyprojecttable);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcB1GeologysvyprojecttableQueryParams queryParams, HttpServletResponse response) {
        List<HddcB1GeologysvyprojecttableEntity> yhDisasterEntities = hddcB1GeologysvyprojecttableNativeRepository.exportYhDisasters(queryParams);
        List<HddcB1GeologysvyprojecttableVO> list=new ArrayList<>();
        for (HddcB1GeologysvyprojecttableEntity entity:yhDisasterEntities) {
            HddcB1GeologysvyprojecttableVO yhDisasterVO=new HddcB1GeologysvyprojecttableVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "地质调查工程表", "地质调查工程表", HddcB1GeologysvyprojecttableVO.class, "地质调查工程表.xls", response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(geologySurveyProjectTableExcelVerifyHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcB1GeologysvyprojecttableVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcB1GeologysvyprojecttableVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcB1GeologysvyprojecttableVO yhDisasterVO : result.getFailList()) {
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcB1GeologysvyprojecttableVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).toString();
        } catch (Exception e) {
            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     */
    public void saveDisasterList(List<HddcB1GeologysvyprojecttableVO> list) {
        for (HddcB1GeologysvyprojecttableVO hddcB1GeologysvyprojecttableVO : list) {
            HddcB1GeologysvyprojecttableEntity yhDisasterEntity = new HddcB1GeologysvyprojecttableEntity();
            BeanUtils.copyProperties(hddcB1GeologysvyprojecttableVO, yhDisasterEntity);
            saveHddcB1Geologysvyprojecttable(yhDisasterEntity);
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcB1GeologysvyprojecttableEntity> hddcDataList = this.hddcB1GeologysvyprojecttableRepository.queryByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcDataList) && hddcDataList.size() > 0) {
            for(HddcB1GeologysvyprojecttableEntity entity : hddcDataList) {
                entity.setUpdateUser(PlatformSessionUtils.getUserId());
                entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                entity.setIsValid(PlatformConstants.N);
                this.hddcB1GeologysvyprojecttableRepository.save(entity);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcB1GeologysvyprojecttableEntity> hddcDataList = this.hddcB1GeologysvyprojecttableRepository.queryByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcDataList) && hddcDataList.size() > 0) {
            for(HddcB1GeologysvyprojecttableEntity entity : hddcDataList) {
                entity.setUpdateUser(PlatformSessionUtils.getUserId());
                entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                entity.setIsValid(PlatformConstants.N);
                this.hddcB1GeologysvyprojecttableRepository.save(entity);
            }
        }
    }
}
